import datetime
from pprint import pprint

from cacheout import Cache

from config import MPConfig, OAConfig, Config
from py_wechat_tools import MPTools, OATools
from py_wechat_tools.libs.tools import LogsConf
from py_wechat_tools.mini_program.updatable_message import TemplateInfo

# config.py 文件为测试用的配置文件，如需测试可自行添加或直接填充值
# 小程序
mp = MPTools(
    appid=MPConfig.APPID,  # 小程序的appid
    secret=MPConfig.SECRET,  # 小程序的密钥
    debug=True,
    passive_access_token=True,  # 是否自动更新access_token
    # access_token=MPConfig.ACCESS_TOKEN
    # get_access_token_url="http://127.0.0.1:8000/api/system/get_access_token"
)

# 公众号
oa = OATools(
    appid=OAConfig.APPID,
    secret=OAConfig.SECRET,
    debug=True,
    passive_access_token=True,  # 是否自动更新access_token
    redirect_uri=OAConfig.REDIRECT_URI,
    access_token=OAConfig.ACCESS_TOKEN,
    cache_obj=Cache(),  # 修改缓存方式，传入缓存对象实例
)


# 示例openid
openid = Config.OPEN_ID


class Wx(MPTools):
    """ 示例：重写MPTools，定制一些方法 """

    def get_access_token_cache(self, access_token=None):
        """
        支持重写access_token缓存方法，修改缓存时间等，最后返回一个access_token 即可
        注意：如需修改缓存方式，可通过重写get_cache方式重写
        :param access_token: 临时access_token，如果传了，以这个access_token为准
        :return: 返回access_token
        """

        access_token = access_token or self.get_cache("access_token")
        if not access_token:
            data = self.get_access_token()
            access_token = data.access_token
            # 缓存1小时，access_token有效时间为7200秒(2小时)，代码里面缓存1小时足够了
            # 最好提前失效重新获取，避免接口出现access_token无效的返回
            self.set_cache("access_token", access_token, 2 * 60 * 60)
        self.access_token = access_token
        return access_token

    # def get_cache(self, key, default=None):
    #     """ 如果获取缓存数据的方式不是 cache.get(key, default)，需要重写该方法 """
    #
    # def set_cache(self, key, value, ttl=None):
    #     """ 如果设置缓存数据的方式不是 cache.set(key, default)，需要重写该方法 """

    def get_logs_conf(self):
        """
        支持重写日志配置
        :return: 返回一个 LogsConf 日志配置类即可
        """
        return LogsConf(
            name="wechat_tools",  # 日志名称
            level=LogsConf.DEBUG,  # 日志级别
            file_path=None,  # 输出日志到文件，None为不输出到文件
            # 格式，参考 logging
            formatter="'%(asctime)s - %(name)s..%(filename)s.%(lineno)d - %(levelname)s: %(message)s'",
            stream_handler=True  # 是否输出到终端
        )


def get_access_token():
    """ 示例：获取access_token """

    # 如果 passive_access_token = True，不需要手动调用该方法
    wechatdata = mp.get_access_token()
    print(wechatdata.access_token)


def code2session():
    """ 示例：code换session """
    # js_code: 小程序调用wx.login()获取的code
    wechatdata = mp.code2session(js_code="0b3Jj310096nPR10eL100BTsf32Jj31L")
    print(wechatdata)


def decrypt():
    """ 示例：解析敏感数据（解析用户信息数据） """
    wechatdata = mp.code2session(js_code="0936ry000b8c4O1S5f300RnDwB06ry0x")
    iv = ""
    data = mp.decrypt(wechatdata, iv, wechatdata.session_key)
    print(data)


def check_encrypted_data():
    """ 示例：检查加密信息是否微信生成（仅手机号加密信息） """
    # 待测试
    encrypted_msg_hash = "657edd868c9715a9be******************************************",

    wechatdata = mp.check_encrypted_data(encrypted_msg_hash=encrypted_msg_hash)
    print(wechatdata)


def get_plugin_open_pid():
    """ 示例：小程序插件code换openid """
    # 待测试
    wechatdata = mp.get_plugin_open_pid(code="")
    print(wechatdata)


def get_phone_number():
    """ 示例：code换手机号 """
    # 待测试
    wechatdata = mp.get_phone_number(
        # 通过小程序getPhoneNumber获取到code, 注意：不是wx.login()获取的code。两个code作用不一样
        code="e1f11c05c754c60a0b62ea******************************************"
    )
    print(wechatdata)
    return wechatdata


def create_activity_id():
    """ 示例：创建被分享动态消息或私密消息的 activity_id """
    mp.create_activity_id(openid=openid)


def set_updatable_msg():
    """ 示例：修改被分享的动态消息 """
    mp.set_updatable_msg(
        activity_id="1172_8T7oUJLg61eRczmwDTN_i7rKSi5ddj93iehmavHbwnn-FFmzYNZw9DOHeAc~",
        target_state=0,
        template_info=TemplateInfo(
            member_count=2,
            room_limit=3,
            # path = 2,
            # version_type = 2,
        )
    )


def get_user_risk_rank():
    """ 示例：根据提交的用户信息数据获取用户的安全等级 risk_rank，无需用户授权。 """
    mp.get_user_risk_rank(
        openid=openid
    )


def generate():
    """ 示例：获取小程序 Short Link """
    mp.generate(
        page_url="pages/index"
    )


def verify_signature():
    """ SOTER 生物认证秘钥签名验证 """
    mp.verify_signature(
        openid=openid,
        json_string='',
        json_signature=""
    )


def create_room():
    """ 创建直播间 """

    # su = mp.superresolution(img_url='https://img2.woyaogexing.com/2022/11/17/30b35ff9df63feb1!400x400.jpg')
    media_id = "EgdX3_-g6NKOPz0h99LpP2MtlOehfYuUomBIr6XjE6YYZsshQy9C5EBJcVvpqX4E"
    """ 创建直播间 """
    room = mp.create_room(
        name="mjinnn直播间",
        coverImg=media_id,
        startTime=datetime.datetime.now() + datetime.timedelta(minutes=11),
        endTime=datetime.datetime.now() + datetime.timedelta(minutes=41),
        # startTime=1668765360,
        # endTime=1668768960,
        anchorName="***",
        anchorWechat="***",
        shareImg=media_id,
        feedsImg=media_id,
    )
    print(room)


def get_live_info():
    """ 获取直播间列表 """
    data = mp.get_live_info()
    print(data)


def delete_room():
    """ 删除直播间 """

    data = mp.delete_room(room_id=2)
    print(data)


def get_push_url():
    """ 获取直播间推流地址 """

    data = mp.get_push_url(room_id=5)
    print(data)


def get_shared_code():
    """ 获取直播间分享二维码 """

    data = mp.get_shared_code(room_id=5)
    print(data)


def get_sub_anchor():
    """ 获取直播副号 """

    data = mp.get_sub_anchor(room_id=5)
    print(data)


def modify_sub_anchor():
    """ 修改主播副号 """

    data = mp.modify_sub_anchor(room_id=5, username="***")
    print(data)


def delete_sub_anchor():
    """ 删除主播副号 """

    data = mp.delete_sub_anchor(room_id=5)
    print(data)


def add_sub_anchor():
    """ 添加主播副号 """

    data = mp.add_sub_anchor(room_id=6, username="aoguoshijian")
    print(data)


def edit_room():
    """ 编辑直播间 """

    media_id = "EgdX3_-g6NKOPz0h99LpP2MtlOehfYuUomBIr6XjE6YYZsshQy9C5EBJcVvpqX4E"
    """ 编辑直播间 """
    room = mp.edit_room(
        room_id=5,
        name="mjinnn直播间编辑",
        coverImg=media_id,
        startTime=datetime.datetime.now() + datetime.timedelta(minutes=11),
        endTime=datetime.datetime.now() + datetime.timedelta(minutes=41),
        # startTime=1668765360,
        # endTime=1668768960,
        anchorName="**",
        anchorWechat="***",
        shareImg=media_id,
        feedsImg=media_id,
    )
    print(room)


def upload_media():
    """ 媒体文件上传到微信临时素材 """
    # with open("/Users/mjinnn/Pictures/0.png", 'rb') as f:
    with open("image.png", 'rb') as f:
        file = f.read()
        name = f.name
    print(name)
    print(file)
    # media = mp.upload_media(file_name=name, file=file)
    media = mp.upload_media("name.png", file_url="https://img2.woyaogexing.com/2022/11/17/30b35ff9df63feb1!400x400.jpg")
    print("媒体》》")
    print(media)


def uploadimg_media():
    """ 上传永久素材 """

    with open("image.png", 'rb') as f:
        file = f.read()
        name = f.name
    # media = mp.upload_media(file_name=name, file=file)
    media = mp.uploadimg_media("name.png", file_url="https://img2.woyaogexing.com/2022/11/17/30b35ff9df63feb1!400x400.jpg")
    print(media)


def get_material():
    """ 获取永久素材 """

    # 图片
    # media = oa.get_material(
    #     media_id="KFch01dc8HRKikHhbLTIBzPsBkaQhE9nAtceENtgU9xc33kqBaxVVbpVfndXj_6P", file_path_name="a.png")
    # 视频
    media = oa.get_material(
        media_id="KFch01dc8HRKikHhbLTIBxpvgEufSFMIbR7QkBMQJQdKBKwPZYfbjSqfvaLF3c5s", file_path_name="b.png")
    print(media)


def del_material():
    """ 获取永久素材 """

    media = oa.del_material(
        media_id="KFch01dc8HRKikHhbLTIBzjinUaO00U-kQpDLZ3H5lZMLCMsMyKwfcug4X7HEGrj")
    print(media)


def get_material_count():
    """ 获取永久素材 """

    media = oa.get_material_count()
    print(media)


def batchget_material():
    """ 获取素材列表 """

    media = oa.batchget_material(page=1, file_type="image")
    pprint(media.result_json)


def batchget_material1():
    """ 新增素材列表 """

    media = oa.batchget_material()
    print(media.result_json)


def superresolution():
    with open("image.png", 'rb') as f:
        file = f.read()
        name = f.name
    mp.superresolution(file_name=name, file=file)


def ai_crop():
    with open("image.png", 'rb') as f:
        file = f.read()
        name = f.name
    mp.ai_crop(file_name=name, file=file)


def scan_qr_code():
    with open("image.png", 'rb') as f:
        file = f.read()
        name = f.name
    mp.scan_qr_code(file_name=name, file=file)


def oa_access_token_cache(data, *args, **kwargs):
    """ 配置缓存 """


def msg_sec_check():
    """ 检查一段文本是否含有违法违规内容 """
    mp.msg_sec_check('oHTPh5aNArOcMMzWwxlQMjqntdyY', 2, 'content')


if __name__ == "__main__":

    # create_room()
    # delete_room()
    # get_material()
    # get_access_token()
    # text/plain
    # get_live_info()
    # code2session()
    msg_sec_check()
